package com.example.redis.service;

import com.example.redis.constant.CommonConstant;
import com.example.redis.entity.OnlineDevices;
import com.example.redis.redis.RedisStringUtil;
import com.example.redis.util.Result;
import io.lettuce.core.RedisConnectionException;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
@Data
@RequiredArgsConstructor
@Slf4j
public class RedisService {
    private final RedisStringUtil redisStringUtil;

    public Result<OnlineDevices> getOnlineDevices(String prefix){
        OnlineDevices onlineDevices=new OnlineDevices();
        Set<String> devices=null;
        try{
            if(prefix==null || prefix.isEmpty()){
                devices=redisStringUtil.getPrefixKeys(CommonConstant.REDIS_PREFIX);
            } else{
                devices=redisStringUtil.getPrefixKeys(prefix);
            }
        } catch (RedisConnectionFailureException e){
            log.error("redis connection failed");
        }
        catch (Exception e){
            log.error("getOnlineDevices Error!",e);
        }

        if(devices==null){
            return Result.fail("Cannot get online devices!");
        }

        onlineDevices.setDevices(devices);
        onlineDevices.setCount(devices.size());

        return Result.ok(onlineDevices);
    }
}
